#!/usr/bin/env python
# -*- coding:utf-8 -*-

# 数据来源: https://github.com/selva86/datasets

import pandas as pd
import numpy as np 
import matplotlib as mpl 
import matplotlib.pyplot as plt 
import seaborn as sns 
import warnings; warnings.filterwarnings(action='once')


# 1.5 排序(RanKing)
# 1.5.1 有序条形图(Ordered Bar Chart)
# 有序条形图有效地传达了项目的排名顺序. 但是,在图表上方添加度量标准的值, 用户可以从图表本身获取精确信息.
"""
# Prepare Data
df_raw = pd.read_csv("F:\\PythonProject\\data\\fromdata\\datasets\\mpg_ggplot2.csv")
df = df_raw[['cty','manufacturer']].groupby('manufacturer').apply(lambda x: x.mean())
df.sort_values('cty',inplace=True)
df.reset_index(inplace=True)

# Draw plot
import matplotlib.patches as patches

fig,ax = plt.subplots(figsize=(16,10),facecolor='white',dpi=80)
ax.vlines(x=df.index,ymin=0,ymax=df.cty,color='firebrick',alpha=0.7,linewidth=20)

# Annotate Text
for i, cty in enumerate(df.cty):
    ax.text(i,cty+0.5,round(cty,1),horizontalalignment='center')

# Title,Label, Ticks and Ylim
ax.set_title('Bar Chart for Highway Mileage',fontdict={'size':22})
ax.set(ylabel='Miles Per Gallon',ylim=(0,30))
plt.xticks(df.index,df.manufacturer.str.upper(),rotation=60,horizontalalignment='right',fontsize=12)

# Add patches to color the X axis labels
p1 = patches.Rectangle((.57,-0.005),width=.33,height=.13,alpha=.1,facecolor='green',transform=fig.transFigure)
p2 = patches.Rectangle((.124,-0.005),width=.446,height=.13,alpha=.1,facecolor='red',transform=fig.transFigure)
fig.add_artist(p1)
fig.add_artist(p2)
plt.savefig("F:\\PythonProject\\AI\\Python\\DataAnalysis\\scripts\\files\\OrderedBarChart.png")
plt.show()
"""



# 1.5.2 棒棒糖图(Lollipop Chart)
# 棒棒糖图表以一种视觉上令人愉悦的方式提供与有序条形图类似的目的.
"""
# Prepare Data
df_raw = pd.read_csv("F:\\PythonProject\\data\\fromdata\\datasets\\mpg_ggplot2.csv")
df = df_raw[['cty','manufacturer']].groupby('manufacturer').apply(lambda x: x.mean())
df.sort_values('cty',inplace=True)

# Draw plot
fig,ax = plt.subplots(figsize=(16,10),dpi=80)
ax.vlines(x=df.index,ymin=0,ymax=df.cty,color='firebrick',alpha=0.7,linewidth=2)
ax.scatter(x=df.index,y=df.cty,s=75,color='firebrick',alpha=0.7)

# Title,Label, Ticks and Ylim
ax.set_title('Lollipop Chart for Highway Mileage',fontdict={'size':22})
ax.set_ylabel('Miles Per Gallon')
ax.set_xticks(df.index)
ax.set_xticklabels(df.manufacturer.str.upper(),rotation=60,fontdict={'horizontalalignment': 'right','size':12})
ax.set_ylim(0,30)

# Annotate
for row in df.itertuples():
    ax.text(row.Index,row.cty+.5,s=round(row.cty,2),horizontalalignment='center',verticalalignment='bottom',fontsize=14)

plt.savefig("F:\\PythonProject\\AI\\Python\\DataAnalysis\\scripts\\files\\LollipopChart.png")
plt.show()

报错:
    return object.__getattribute__(self, name)
AttributeError: 'DataFrame' object has no attribute 'manufacturer'
The terminal process terminated with exit code: 1
"""






# 1.5.3 包点图(Dot Plot)
# 包点图表传达了项目的排名顺序,并且由于它沿水平轴对其,因此可以看到点彼此之间的距离.
"""
# Prepare Data
df_raw = pd.read_csv("F:\\PythonProject\\data\\fromdata\\datasets\\mpg_ggplot2.csv")
df = df_raw[['cty','manufacturer']].groupby('manufacturer').apply(lambda x: x.mean())
df.sort_values('cty',inplace=True)
df.reset_index(inplace=True)

# Draw plot
fig,ax = plt.subplots(figsize=(16,10),dpi=80)
ax.hlines(y=df.index,xmin=11,xmax=26,color='gray',alpha=0.7,linewidth=1,linestyles='dashdot')
ax.scatter(y=df.index,x=df.cty,s=75,color='firebrick',alpha=0.7)

# Title, Label,Ticks and Ylim
ax.set_title('Dot Plot for Highway Mileage',fontdict={'size':22})
ax.set_xlabel('Miles Per Gallon')
ax.set_yticks(df.index)
ax.set_yticklabels(df.manufacturer.str.title(),fontdict={'horizontalalignment': 'right'})
ax.set_xlim(10,27)
plt.savefig("F:\\PythonProject\\AI\\Python\\DataAnalysis\\scripts\\files\\DotPlot.png")
plt.show()
"""




# 1.5.4 坡度图(Slope Chart)
# 坡度图适合比较给定人/项目的"前"和"后"位置.
import matplotlib.lines as mlines
# Import Data
df = pd.read_csv("F:\\PythonProject\\data\\fromdata\\datasets\\gdppercap.csv")
left_label = [str(c) + ', ' + str(round(y)) for c,y in zip(df.continent,df['1952'])]
right_label = [str(c) + ', ' + str(round(y)) for c,y in zip(df.continent,df['1957'])]
klass = ['red' if (y1-y2) < 0 else 'green' for y1,y2 in zip(df['1952'],df['1957'])]

# draw line
def newline(p1,p2,color='black'):
    ax = plt.gca()
    l = mlines.Line2D([p1[0],p2[0]],[p1[1],p2[1]],color='red' if p1[1]-p2[1] > 0 else 'green',marker='o',markersize=6)
    ax.add_line(l)
    return l

fig,ax = plt.subplots(1,1,figsize=(14,14),dpi=80)

# Vertical Lines
ax.vlines(x=1,ymin=500,ymax=13000,color='black',alpha=0.7,linewidth=1,linestyles='dotted')
ax.vlines(x=3,ymin=500,ymax=13000,color='black',alpha=0.7,linewidth=1,linestyles='dotted')

# Points
ax.scatter(y=df['1952'],x=np.repeat(1,df.shape[0]),s=10,color='black',alpha=0.7)
ax.scatter(y=df['1957'],x=np.repeat(3,df.shape[0]),s=10,color='black',alpha=0.7)

# Line Segmentsand Annotation
for p1,p2,c in zip(df['1952'],df['1957'],df['continent']):
    newline([1,p1],[3,p2])
    ax.text(1-0.05,p1,c + ', ' + str(round(p1)),horizontalalignment='right',verticalalignment='center',fontdict={'size':14}) 
    ax.text(3+0.05,p2, c + ', ' + str(round(p2)),horizontalalignment='left',verticalalignment='center',fontdict={'size':14})

# 'Before' and 'After' Annotations
ax.text(1-0.05,13000,'BEFORE', horizontalalignment='right',verticalalignment='center',fontdict={'size':18,'weight':700})
ax.text(3+0.05,13000,'AFTER',horizontalalignment='left',verticalalignment='center',fontdict={'size':18,'weight':700})

# Decoration
ax.set_title("Slopechart: Comparing GDP Per Capita between 1952 vs 1957",fontdict={'size':22})
ax.set(xlim=(0,4),ylim=(0,14000),ylabel='Mean GDP Per Capita')
ax.set_xticks([1,3])
ax.set_xticklabels(["1952","1957"])
plt.yticks(np.arange(500,13000,2000),fontsize=12)

# Lighten borders
plt.gca().spines["top"].set_alpha(.0)
plt.gca().spines["bottom"].set_alpha(.0)
plt.gca().spines["right"].set_alpha(.0)
plt.gca().spines["left"].set_alpha(.0)
plt.savefig("F:\\PythonProject\\AI\\Python\\DataAnalysis\\scripts\\files\\SlopeChart.png")
plt.show()

